<script lang='ts' setup>
import { shikiToMonaco } from '@shikijs/monaco'
import * as monaco from 'monaco-editor-core';
import { createHighlighter } from 'shiki'
let editor: monaco.editor.IStandaloneCodeEditor
const editorRef = ref()
const props = defineProps<{
  modelValue: string
}>()

const emit = defineEmits(['update:modelValue'])
// const isDark = useDark()
async function intMonacoEditor() {
  const highlighter = await createHighlighter({
    themes: [
      'vitesse-dark',
      'vitesse-light',
    ],
    langs: [
      'java',
      'javascript',
      'typescript',
      'vue'
    ],
  })
  // watch(isDark, () =>{
  //   editor.value?.updateOptions({
  //     theme: isDark.value ? 'vitesse-dark' : 'vitesse-light'
  //   })
  // }, {
  //   immediate: true
  // })

  // 首先注册你需要的语言的 IDs
  monaco.languages.register({ id: 'vue' })
  monaco.languages.register({ id: 'typescript' })
  monaco.languages.register({ id: 'javascript' })
  monaco.languages.register({ id: 'java' })

  // 注册 Shiki 主题，并为 Monaco 提供语法高亮
  shikiToMonaco(highlighter, monaco)

  // 创建编辑器
  editor = monaco.editor.create(editorRef.value, {
    value: props.modelValue,
    language: 'javascript',
    theme: 'vitesse-light',
  })

  editor.onDidChangeModelContent(() => {
    emit('update:modelValue', editor.getValue())
  })

  window.addEventListener('resize', () => {
    editor.layout()
  })
}

defineExpose({
  setValue(val: string) {
    editor.setValue(val)
  },
  getEditor() {
    return editor
  }
})



onMounted(() => {
  intMonacoEditor()
})

onBeforeUnmount(() => {
  editor?.dispose()
})


</script>

<template >
  <div ref="editorRef" class="monaco-editor-container"></div>
</template>

<style>
.monaco-editor-container {
  width: 100%;
  height: 100%;
}

.monaco-editor-container .monaco-editor {
  width: 100% !important;
}
</style>
